package com.yc.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.yc.mapper.CategoryMapper;
import com.yc.model.Category;
import com.yc.service.CategoryService;
import com.yc.web.api.FileUploadApi;
import com.yc.web.api.IdGeneratorApi;
import com.yc.web.bean.CategoryDTO;
import com.yc.web.bean.ResponseResult;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private IdGeneratorApi idGenerator;

    @Autowired
    private FileUploadApi fileUploadApi;
    /**
     * 新增类别
     * @param categoryDTO 待新增的类别信息
     * @return 新增成功后的类别DTO
     */
    @Override
    public CategoryDTO addCategory(CategoryDTO categoryDTO) {
        ResponseResult rr= this.idGenerator.getNextId();
        if(  rr.getCode()!=1){
            throw new RuntimeException("类别ID生成失败");
        }
        Long categoryId =Long.parseLong(rr.getData().toString());
        categoryDTO.setCategoryId(categoryId);

        // 2. 模拟图片上传并设置URL
        ResponseResult rr2= this.fileUploadApi.upload(   new MultipartFile[]{ categoryDTO.getIconFile() });
        if(  rr2.getCode()!=1){
            throw new RuntimeException("类别主图片上传失败");
        }
        List<String> mainImages= (List<String>) rr2.getData();
        categoryDTO.setIcon(   mainImages.get(0)  );
        // 3. 设置状态
        if(categoryDTO.getCategoryStatus()==null){
            categoryDTO.setCategoryStatus(1);
        }

        Category category = new Category();
        BeanUtils.copyProperties(categoryDTO, category);
        int result=categoryMapper.insert(category);
        if(result>0){
            // 插入成功后，返回包含完整信息的DTO
            BeanUtils.copyProperties(category, categoryDTO);
            return categoryDTO;
        }else {
            throw new RuntimeException("新增类别失败");
    }
    }
    /**
     * 查询所有类别
     * @return 所有类别DTO的列表
     */
    @Override
    public List<CategoryDTO> getAllCategories(Integer categoryStatus) {
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        if(categoryStatus!=null){
            queryWrapper.eq(Category::getCategoryStatus, categoryStatus); // 只查询状态为正常的类别
        }
        List<Category> categories = categoryMapper.selectList(queryWrapper);
        // 将实体列表转换为DTO列表
        return categories.stream()
                .map(category -> {
                    CategoryDTO dto = new CategoryDTO();
                    BeanUtils.copyProperties(category, dto);
                    return dto;
                })
                .collect(Collectors.toList());
    }

    /**
     * 修改类别状态
     * @param categoryId 类别ID
     * @return 是否设置成功
     */
    @Override
    public boolean setCategoryStatusToHidden(Long categoryId, Integer status) {
        LambdaUpdateWrapper<Category> queryWrapper = new LambdaUpdateWrapper<>();
       queryWrapper.eq(Category::getCategoryId, categoryId)
               .set(Category::getCategoryStatus, status);
       int result= categoryMapper.update(null, queryWrapper);
       return result>0;
    }

    /**
     * 更新类别信息
     * @param categoryDTO 待更新的类别信息
     * @return 更新成功后的类别DTO
     */
    @Override
    public CategoryDTO updateCategory(CategoryDTO categoryDTO) {
        if (categoryDTO.getCategoryId() == null) {
            throw new IllegalArgumentException("类别ID不能为空，无法更新");
        }

        if( categoryDTO.getIconFile()!=null ) {
            ResponseResult rr2 = this.fileUploadApi.upload(new MultipartFile[]{categoryDTO.getIconFile()});
            if (rr2.getCode() != 1) {
                throw new RuntimeException("类别主图片上传失败");
            }
            List<String> mainImages = (List<String>) rr2.getData();
            categoryDTO.setIcon(mainImages.get(0));
        }

        Category category = new Category();
        BeanUtils.copyProperties(categoryDTO, category);
        int result = categoryMapper.updateById(category);
        if(result>0){
            // 更新成功后，返回最新的类别信息
            return getCategoryById(categoryDTO.getCategoryId());
        }else {
            throw new RuntimeException("类别更新失败，类别ID: " + categoryDTO.getCategoryId());
        }
    }

        /**
         * 根据ID获取类别详情
         * @param categoryId 类别ID
         * @return 类别DTO
         */
    @Override
    public CategoryDTO getCategoryById(Long categoryId) {
        Category category = categoryMapper.selectById(categoryId);
        if (category == null) {
            return null;
        }
        CategoryDTO dto = new CategoryDTO();
        BeanUtils.copyProperties(category, dto);
        return dto;
    }
}
